package com.example.tencent.location

import android.content.Context
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.amap.lib.base.utils.LogUtil
import com.example.amap.location.bean.LocationInfo
import com.example.amap.location.observer.ILocationObserver
import com.example.amap.service.ILocationService
import com.example.tencent.ext.toLocationInfo
import com.tencent.map.fusionlocation.model.TencentGeoLocation
import com.tencent.navix.api.NavigatorZygote
import com.tencent.navix.api.location.GeoLocationObserver
import com.tencent.navix.api.location.LocationApi

@Route(path = "/location/tencent/LocationServiceImpl")
class LocationServiceImpl : ILocationService, GeoLocationObserver() {
    companion object {
        private const val TAG = "LocationServiceImpl"
    }

    private lateinit var mLocationService: LocationApi

    private var mLocationInfo: LocationInfo? = null

    private var mContext: Context? = null

    private val observers = mutableSetOf<ILocationObserver>()

    override fun init(context: Context?) {
        mContext = context
    }

    override fun init() {
        mLocationService = NavigatorZygote.with(mContext?.applicationContext).locationApi()
        mLocationService.apply {
            addLocationObserver(this@LocationServiceImpl, 1000)
        }
    }

    override fun addLocationObserver(observer: ILocationObserver) {
        LogUtil.d(TAG, "addLocationObserver observer: $observer")
        observers.add(observer)
    }

    override fun removeLocationObserver(observer: ILocationObserver) {
        LogUtil.d(TAG, "removeLocationObserver observer: $observer")
        observers.remove(observer)
    }

    override fun getLocationInfo(): LocationInfo? = mLocationInfo

    override fun onGeoLocationChanged(p0: TencentGeoLocation?) {
        mLocationInfo = p0?.location?.toLocationInfo()
        observers.forEach { it.onLocationChanged(mLocationInfo) }
    }
}